const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const WebpackBar = require('webpackbar')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const FontsPlugin = require('./plugins/fonts-plugin')

module.exports = function (env, argv) {
    return {
        mode: env.production ? 'production' : 'development',
        devtool: env.production ? undefined : 'eval',
        entry: path.resolve(__dirname, 'src/js/main.js'),
        output: {
            clean: true,
            path: path.join(__dirname, 'dist'),
            filename: 'js/bundle.[contenthash:8].js',
            chunkFilename: 'js/[name].[contenthash:8].js',
            assetModuleFilename: 'assets/[contenthash:8][ext][query]'
        },
        devServer: {
            static: path.resolve(__dirname, 'dist'),
            hot: true
        },
        module: {
            rules: [
                {
                    test: /\.css$/i,
                    use: [
                        MiniCssExtractPlugin.loader,
                        {
                            loader: 'css-loader',
                            options: {
                                importLoaders: 1
                            }
                        },
                        {
                            loader: 'postcss-loader',
                            options: {
                                postcssOptions: {
                                    plugin: [
                                        ['postcss-preset-env', {}]
                                    ]
                                }
                            }
                        }
                    ],
                },
                {
                    test: /\.(png|svg|jpg|jpeg|gif)$/i,
                    type: 'asset/resource',
                    generator: {
                        filename: 'images/[contenthash:8][ext][query]'
                    }
                },
                {
                    test: /\.(mp3)$/i,
                    type: 'asset/resource'
                },
                {
                    test: /\.(woff|woff2|eot|ttf|otf)$/i,
                    type: 'asset/resource',
                    generator: {
                        filename: 'font/[contenthash:8][ext][query]'
                    }
                }
            ],
        },
        plugins: [
            new WebpackBar(),
            new HtmlWebpackPlugin({
                template: path.resolve(__dirname, 'src/index.html')
            }),
            new MiniCssExtractPlugin({
                filename: 'css/[name].[contenthash:8].css',
            }),
            new FontsPlugin({
                production: env.production
            })
        ],
        experiments: {
            topLevelAwait: true
        }
    }
}
